<template>
  <div id="post-area">
    <div class="post-header">
      <!-- 新增按钮 -->
      <el-button
        type="primary"
        @click="dialogAddFormVisible = true"
        style="margin-right: 10px"
        >新增</el-button
      >
      <!-- 查询框 -->
      <el-input
        placeholder="请输入内容"
        prefix-icon="el-icon-search"
        v-model="searchContent"
        style="width: 200px; margin-right: 10px"
      >
      </el-input>
      <!-- 查找按钮 -->
      <el-button type="primary" @click="searchPosts(searchContent)"
        >查找</el-button
      >
    </div>

    <!-- 新增弹出框 -->
    <el-dialog title="新增帖子" :visible.sync="dialogAddFormVisible">
      <el-form
        :model="addPostForm"
        :rules="rules"
        ref="addPostForm"
        label-position="right"
      >
        <!-- 发帖人输入框 -->
        <el-form-item
          label="发帖人"
          :label-width="formLabelWidth"
          prop="poster"
        >
          <el-input
            v-model="addPostForm.poster"
            autocomplete="off"
            style="width: 200px"
          ></el-input>
        </el-form-item>

        <!-- 标题输入框 -->
        <el-form-item
          label="帖子标题"
          :label-width="formLabelWidth"
          prop="title"
        >
          <el-input
            v-model="addPostForm.title"
            autocomplete="off"
            style="width: 400px"
          ></el-input>
        </el-form-item>

        <!-- 内容文本框 -->
        <el-form-item
          label="帖子内容"
          :label-width="formLabelWidth"
          prop="content"
        >
          <el-input
            type="textarea"
            v-model="addPostForm.content"
            autocomplete="off"
            style="width: 400px"
          ></el-input>
        </el-form-item>

        <!-- 评论输入框 -->
        <div v-for="(item, index) in addPostForm.comments" :key="index">
          <el-form-item :label="'帖子评论' + (index + 1)" label-width="120px">
            <el-input v-model="item.comment" style="width: 400px"></el-input>
            <!-- 新增删除按钮部分 -->
            <el-button
              v-if="index + 1 == addPostForm.comments.length"
              type="primary"
              @click="addItem(addPostForm.comments.length)"
              style="margin-left: 10px"
              size="mini"
              >新增</el-button
            >
            <el-button
              v-if="index !== 0"
              type="danger"
              @click="deleteItem(item, index)"
              style="margin-left: 10px"
              size="mini"
              >删除</el-button
            >
          </el-form-item>
        </div>

        <!-- 标签级联选择器 -->
        <el-form-item
          label="帖子标签"
          :label-width="formLabelWidth"
          prop="tags"
        >
          <el-cascader
            v-model="addPostForm.tags"
            :options="options"
            :props="props"
            collapse-tags
            clearable
          ></el-cascader>
        </el-form-item>

        <!-- 状态下拉列表 -->
        <el-form-item
          label="帖子状态"
          :label-width="formLabelWidth"
          prop="state"
        >
          <el-select v-model="addPostForm.state" placeholder="请选择状态">
            <el-option label="待审核" value="待审核"></el-option>
            <el-option label="审核通过" value="审核通过"></el-option>
            <el-option label="审核未通过" value="审核未通过"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- 新增弹出框取消按钮 -->
        <el-button @click="dialogAddFormVisible = false"> 取 消 </el-button>
        <!-- 新增弹出框确认按钮 -->
        <el-button
          type="primary"
          @click="
            dialogAddFormVisible = false;
            submitAddForm('addPostForm');
          "
        >
          确 定
        </el-button>
      </div>
    </el-dialog>

    <!-- 修改弹出框 -->
    <el-dialog title="修改帖子" :visible.sync="dialogModifyFormVisible">
      <el-form
        :model="modifyPostForm"
        :rules="rules"
        ref="modifyPostForm"
        label-position="right"
      >
        <!-- 发帖人输入框 -->
        <el-form-item
          label="发帖人"
          :label-width="formLabelWidth"
          prop="poster"
        >
          <el-input
            v-model="modifyPostForm.poster"
            autocomplete="off"
            style="width: 200px"
          ></el-input>
        </el-form-item>

        <!-- 标题输入框 -->
        <el-form-item
          label="帖子标题"
          :label-width="formLabelWidth"
          prop="title"
        >
          <el-input
            v-model="modifyPostForm.title"
            autocomplete="off"
            style="width: 400px"
          ></el-input>
        </el-form-item>

        <!-- 内容文本框 -->
        <el-form-item
          label="帖子内容"
          :label-width="formLabelWidth"
          prop="content"
        >
          <el-input
            type="textarea"
            v-model="modifyPostForm.content"
            autocomplete="off"
            style="width: 400px"
          ></el-input>
        </el-form-item>

        <!-- 评论输入框 -->
        <div v-for="(item, index) in modifyPostForm.comments" :key="index">
          <el-form-item :label="'帖子评论' + (index + 1)" label-width="120px">
            <el-input v-model="item.comment" style="width: 400px"></el-input>
            <!-- 新增删除按钮部分 -->
            <el-button
              v-if="index + 1 == modifyPostForm.comments.length"
              type="primary"
              @click="addItem(modifyPostForm.comments.length)"
              style="margin-left: 10px"
              size="mini"
              >新增</el-button
            >
            <el-button
              v-if="index !== 0"
              type="danger"
              @click="deleteItem(item, index)"
              style="margin-left: 10px"
              size="mini"
              >删除</el-button
            >
          </el-form-item>
        </div>

        <!-- 标签级联选择器 -->
        <el-form-item
          label="帖子标签"
          :label-width="formLabelWidth"
          prop="tags"
        >
          <el-cascader
            v-model="modifyPostForm.tags"
            :options="options"
            :props="props"
            collapse-tags
            clearable
          ></el-cascader>
        </el-form-item>

        <!-- 状态下拉列表 -->
        <el-form-item
          label="帖子状态"
          :label-width="formLabelWidth"
          prop="state"
        >
          <el-select v-model="modifyPostForm.state" placeholder="请选择状态">
            <el-option label="待审核" value="待审核"></el-option>
            <el-option label="审核通过" value="审核通过"></el-option>
            <el-option label="审核未通过" value="审核未通过"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- 修改弹出框取消按钮 -->
        <el-button @click="dialogModifyFormVisible = false"> 取 消 </el-button>
        <!-- 修改弹出框确认按钮 -->
        <el-button
          type="primary"
          @click="
            dialogModifyFormVisible = false;
            submitModifyForm('modifyPostForm');
          "
        >
          确 定
        </el-button>
      </div>
    </el-dialog>

    <!-- 表格内容 -->
    <el-table :data="showData" stripe style="width: 100%">
      <el-table-column prop="poster" label="发帖人"> </el-table-column>
      <el-table-column prop="title" label="标题" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="content" label="内容" show-overflow-tooltip>
      </el-table-column>
      <el-table-column
        prop="tags"
        label="标签"
        :formatter="tagsData"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="comments"
        label="评论"
        :formatter="commentsData"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="发帖时间"
        :formatter="createTimeData"
        min-width="110px"
      >
      </el-table-column>
      <el-table-column prop="state" label="状态"> </el-table-column>
      <el-table-column label="操作" min-width="90px">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  data() {
    return {
      // 表单域标签的宽度设置
      formLabelWidth: "120px",
      // 新增对话框是否显示
      dialogAddFormVisible: false,
      // 新增表单数据初始化
      addPostForm: {
        poster: "",
        title: "",
        content: "",
        tags: [],
        comments: [{ comment: "" }],
        createTime: "",
        _id: "",
      },
      // 新增对话框是否显示
      dialogModifyFormVisible: false,
      // 修改表单数据初始化
      modifyPostForm: {
        poster: "",
        title: "",
        content: "",
        tags: [],
        comments: [{ comment: "" }],
        createTime: "",
      },
      // 级联选择器的配置选项
      props: {
        multiple: true, // 是否多选
      },
      // 级联选择器的可选项数据源
      options: [
        { value: "政治", label: "政治" },
        { value: "外交", label: "外交" },
        { value: "体育", label: "体育" },
        { value: "娱乐", label: "娱乐" },
      ],
      // 表单验证规则
      rules: {
        poster: [
          { required: true, message: "请输入发帖用户名", trigger: "blur" },
        ],
        title: [{ required: true, message: "请输入帖子主题", trigger: "blur" }],
        content: [
          { required: true, message: "请输入帖子内容", trigger: "change" },
        ],
        // comments: [
        //   { required: true, message: "请选择时间", trigger: "change" },
        // ],
        tags: [
          {
            required: true,
            message: "请至少选择一个标签",
            type: "array",
            trigger: "change",
          },
        ],
        state: [{ required: true, message: "请选择状态", trigger: "change" }],
      },
      // 查询框
      searchContent: "",
    };
  },
  computed: {
    ...mapState("postStore", ["posts"]),
    showData() {
      return this.posts;
    },
  },
  methods: {
    // 修改帖子
    handleEdit(index, row) {
      console.log(index, row);
      this.modifyPostForm = {
        poster: row.poster,
        title: row.title,
        content: row.content,
        comments: row.comments.map((item) => {
          return { comment: item };
        }),
        createTime: row.createTime,
        state: row.state,
        tags: row.tags,
        _id: row._id,
      };
      console.log(this.modifyPostForm);
      this.dialogModifyFormVisible = true;
    },

    // 删除帖子
    handleDelete(index, row) {
      console.log(index, row);
      this.$store.dispatch("postStore/deletePostAsync", row._id);
      this.$router.go(0);
    },

    // 对标签数组进行分割处理
    tagsData(row) {
      let tagArr = [];
      row.tags.forEach((item) => {
        tagArr.push("#" + item);
      });
      return tagArr;
    },

    // 对评论数组进行分割处理
    commentsData(row) {
      let commentArr = [];
      row.comments.forEach((item) => {
        commentArr.push("#" + item);
      });
      return commentArr;
    },

    // 对数据库的发帖时间格式进行处理
    createTimeData(row) {
      console.log(row.createTime);
      let newTime = row.createTime.split("T").join(" ");
      return newTime.slice(0, newTime.length - 5);
    },

    // 对话框新增评论
    addItem(length) {
      console.log(this.addPostForm.comments.length);
      if (length >= 10) {
        this.$message({
          type: "warning",
          message: "最多可新增10条!",
        });
      } else {
        this.addPostForm.comments.push({
          comment: "",
        });
      }
    },

    // 对话框删除评论
    deleteItem(item, index) {
      this.addPostForm.comments.splice(index, 1);
    },

    // 提交新增对话框的表单
    submitAddForm(formName) {
      this.addPostForm.comments = this.addPostForm.comments.map(
        (item) => item.comment
      );
      this.addPostForm.tags = this.addPostForm.tags.map((item) => item[0]);
      this.addPostForm.createTime = this.getNowDate();
      console.log(this.addPostForm);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$store.dispatch("postStore/addPostAsync", this.addPostForm);
          // .then(() => this.$router.push("/posts"));
          this.$router.go(0);
        } else {
          alert("不符合新增要求");
          return false;
        }
      });
    },

    // 提交修改对话框的表单
    submitModifyForm(formName) {
      this.modifyPostForm.comments = this.modifyPostForm.comments.map(
        (item) => item.comment
      );
      this.modifyPostForm.tags = this.modifyPostForm.tags.map(
        (item) => item[0]
      );
      this.modifyPostForm.createTime = this.getNowDate();
      console.log(this.modifyPostForm);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$store.dispatch(
            "postStore/modifyPostAsync",
            this.modifyPostForm
          );
          this.$router.go(0);
        } else {
          this.$message({
            showClose: true,
            message: "修改失败",
            type: "error",
          });
        }
      });
    },

    // 查询日期
    getNowDate() {
      const date = new Date();
      let year = date.getFullYear(); // 年
      let month = date.getMonth() + 1; // 月
      let day = date.getDate(); // 日
      let hour = date.getHours(); // 时
      let minutes = date.getMinutes(); // 分
      let seconds = date.getSeconds(); // 秒
      // 统一格式
      month = month < 10 ? "0" + month : month;
      day = day < 10 ? "0" + day : day;
      hour = hour < 10 ? "0" + hour : hour;
      minutes = minutes < 10 ? "0" + minutes : minutes;
      seconds = seconds < 10 ? "0" + seconds : seconds;
      return (
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hour +
        ":" +
        minutes +
        ":" +
        seconds
      );
    },

    // 查询帖子
    searchPosts(content) {
      console.log(content);
      let result = this.posts.filter(
        (item) =>
          item.title.includes(content) ||
          item.content.includes(content) ||
          item.poster.includes(content)
      );
      console.log(result);
      this.$store.commit("postStore/setPosts", result);
    },
  },
};
</script>

<style scoped>
#post-area .el-dialog {
  height: 78px;
  overflow: auto;
}
</style>
